package com.freesaas.merchant.action;

import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fast.common.xml.XmlUtil;
import com.freesaas.merchant.service.CreateOrderService;
import com.freesaas.merchant.vo.P00201Request;
import com.freesaas.merchant.vo.P00201Response;
import com.payment.channel.vo.WechatPayCallbackResponse;

@Controller
public class P002Action {

	private Logger logger = LoggerFactory.getLogger(P002Action.class);

	@Autowired
	private CreateOrderService orderService;

	/**
	 * @param p00201Req
	 * @param request
	 *            保存支付订单
	 */
	@RequestMapping(value = "/P00201", method = RequestMethod.POST)
	@ResponseBody
	public P00201Response P00201(P00201Request p00201Req, HttpServletRequest request) {
		String userAgent = request.getHeader("User-Agent");
		logger.info("浏览器信息：{}", userAgent);
		logger.info("请求IP：{}", request.getRemoteAddr());
		String remoteIp = request.getRemoteAddr();
		String busTyp = null;
		if (userAgent.indexOf("MicroMessenger") > 0) {
			busTyp = "1001";
		} else if (userAgent.indexOf("AlipayClient") > 0 || userAgent.indexOf("AliApp") > 0
				|| userAgent.indexOf("AlipayDefined") > 0) {
			busTyp = "1002";
		}
		P00201Response response = new P00201Response();
		Map<String, String> retmap = null;
		try {
			retmap = orderService.P00201(p00201Req, remoteIp, busTyp);
		} catch (Exception e) {
			response.setRespCode("ERR999");
			response.setRespMsg("系统异常");
			return response;
		}

		response.setJsapi(retmap);
		return response;
	}

	/**
	 * @param p00201Req
	 * @param request
	 *            支付回调
	 * @throws IOException
	 */
	@RequestMapping(value = "/P00201", method = RequestMethod.POST)
	@ResponseBody
	public String P00201(HttpServletRequest request, @RequestBody String body) throws IOException {
		WechatPayCallbackResponse response = new WechatPayCallbackResponse();
		logger.info("请求报文：{}", body);
		logger.info("请求IP：{}", request.getRemoteAddr());
		try {
			orderService.P00202(body);
		} catch (Exception e) {
			logger.error("", e);
			response.setReturnCode("FAIL");
			response.setReturnMsg("签名失败");
			return XmlUtil.toXml(response);
		}
		response.setReturnCode("SUCCESS");
		response.setReturnMsg("OK");
		return XmlUtil.toXml(response);
	}
}
